#include "libqueue.h"

static int msqid;

int crearCola() {

	if((msqid = msgget(IPC_PRIVATE,0644)) == -1) {
		perror("msgget");
		exit(1);
	}
	fflush(stdout);
	return msqid;
}

void enviarMsj(long mtype, int action, int pid, const char * data) {
	msj buf; 

	buf.mtype = mtype;
	buf.info.action = action;
	buf.info.pid = pid;
	if(data != NULL) {
		strcpy(buf.info.data,data);
	}
	
	if(msgsnd(msqid,&buf,sizeof(infoMsj),0) == -1) {
		perror("msgsnd");
		exit(1);
	}
}

infoMsj recibirMsj(long mstype) {
	msj buf; 
	
	if (msgrcv(msqid,&buf, sizeof(infoMsj), mstype, 0) == -1) {
	  	perror("msgrcv");
	  	exit(1);
	}
	fflush(stdout);
  
	return buf.info;
}

void dumpMsj(long mstype) {
	msj nuevoMsj;
	
	while(msgrcv(msqid,(msj *)&nuevoMsj, sizeof(infoMsj),mstype, IPC_NOWAIT) != -1)
	;   
}

void abrirCola(int mqueueid) {
	msqid=mqueueid;
}

void destruirCola() {
	msgctl(msqid, IPC_RMID, NULL);
}
